package cool.taomu.platform.common

import cool.taomu.platform.common.service.MenuService
import cool.taomu.toolkit.utils.FileTools
import java.util.function.Function
import javax.inject.Inject
import javax.inject.Named
import org.apache.commons.io.IOUtils
import org.apache.commons.vfs2.FileSystemManager

abstract class BaseController {
    @Inject
    @Named("taomu.http.pathSpec")
    protected String pathSpec;

    @Inject
    @Named("taomu.title")
    protected String title

    @Inject
    protected FileSystemManager fsManager

    @Inject
    protected MenuService menuService;

    def loadTemplate(String name, String path, Function<String, String> func) {
        try(var fobject = fsManager.resolveFile("res://template/stock.html")) {
            var a = IOUtils.toString(fobject.content.inputStream, "UTF-8");
            a = FileTools.extractBetweenComments(a, "<!-- PAGE CONTENT BEGINS -->", "<!-- PAGE CONTENT ENDS -->")
            if (func !== null) {
                a = func.apply(a);
            }
            return #{"pathSpec" -> pathSpec, "title" -> title, "menus" -> menuService.menuList, "navbar" -> "nav",
                "content" -> a, "userid" -> "0", "name" -> name}
        }
    }
}
